<template>
  <view class="container">
    <view class="header">您好，欢迎注册！</view>

    <view class="login-type-switch">
      <view class="switch-container">
        <view
          :class="['switch-option', registerForm.role === 'USER' ? 'active' : '']"
          @tap="switchRole('USER')"
        >
          用户注册
        </view>
        <view
          :class="['switch-option', registerForm.role === 'EMPLOY' ? 'active' : '']"
          @tap="switchRole('EMPLOY')"
        >
          企业注册
        </view>
      </view>
    </view>

    <view class="form">
      <view class="input-group">
        <text class="label">{{ registerForm.role === 'USER' ? '邮箱' : '企业邮箱' }}</text>
        <input
          type="text"
          v-model="registerForm.email"
          :placeholder="registerForm.role === 'USER' ? '请输入邮箱' : '请输入企业邮箱'"
          @blur="validateEmail"
        />
        <text class="error-message" v-if="errors.email">{{ errors.email }}</text>
      </view>

      <view class="input-group">
        <text class="label">验证码</text>
        <view class="code-wrapper">
          <input
            type="text"
            v-model="registerForm.code"
            placeholder="请输入验证码"
            @blur="validateCode"
			style="border: none;"
          />
          <view
            class="code-btn"
            @tap="getCode"
            :disabled="counting"
          >
            {{ counting ? `${countdown}s` : '获取验证码' }}
          </view>
        </view>
        <text class="error-message" v-if="errors.code">{{ errors.code }}</text>
      </view>

      <view class="input-group">
        <text class="label">密码</text>
        <input
          type="password"
          v-model="registerForm.password"
          placeholder="请设置密码"
          @blur="validatePassword"
        />
        <text class="error-message" v-if="errors.password">{{ errors.password }}</text>
      </view>

      <view class="input-group">
        <text class="label">确认密码</text>
        <input
          type="password"
          v-model="registerForm.confirmPassword"
          placeholder="请再次输入密码"
          @blur="validateConfirm"
        />
        <text class="error-message" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</text>
      </view>
    </view>

    <button class="login-btn" @tap="handleRegister">注册</button>

    <view class="switch-form">
      <view @tap="goLogin">已有账号？<text class="switch-btn">立即登录</text></view>
    </view>

    <view class="footer">
      注册即表明同意隐私协议和用户服务协议
    </view>
  </view>
</template>

<script>
import { sendCode } from '@/api/login.js'
import { register } from '@/api/register.js'

export default {
  data() {
    return {
      registerForm: {
        role: 'USER', // USER / EMPLOY
        email: '',
        code: '',
        password: '',
        confirmPassword: ''
      },
      errors: {
        email: '',
        code: '',
        password: '',
        confirmPassword: ''
      },
      countdown: 60,
      counting: false,
      timer: null
    }
  },
  methods: {
    switchRole(role) {
      this.registerForm.role = role
      this.clearErrors()
      Object.keys(this.registerForm).forEach(k => { if (k !== 'role') this.registerForm[k] = '' })
      this.resetCountdown()
    },

    validateEmail() {
      const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!this.registerForm.email) {
        this.errors.email = this.registerForm.role === 'USER' ? '请输入邮箱' : '请输入企业邮箱'
        return false
      }
      if (!reg.test(this.registerForm.email)) {
        this.errors.email = '邮箱格式不正确'
        return false
      }
      this.errors.email = ''
      return true
    },

    validateCode() {
      if (!this.registerForm.code) {
        this.errors.code = '请输入验证码'
        return false
      }
      if (this.registerForm.code.length < 4) {
        this.errors.code = '验证码格式不正确'
        return false
      }
      this.errors.code = ''
      return true
    },

    validatePassword() {
      if (!this.registerForm.password) {
        this.errors.password = '请设置密码'
        return false
      }
      if (this.registerForm.password.length < 6) {
        this.errors.password = '密码至少6位'
        return false
      }
      this.errors.password = ''
      return true
    },

    validateConfirm() {
      if (!this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '请再次输入密码'
        return false
      }
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致'
        return false
      }
      this.errors.confirmPassword = ''
      return true
    },

    async getCode() {
      if (!this.validateEmail()) return
      if (this.counting) return

      try {
        uni.showLoading({ title: '发送中...' })
        const res = await sendCode(this.registerForm.email)
        uni.hideLoading()
        if (res.code === 200) {
          uni.showToast({ title: '验证码已发送', icon: 'success' })
          this.startCountdown()
        } else {
          uni.showToast({ title: res.message || '发送失败', icon: 'none' })
        }
      } catch (e) {
        uni.hideLoading()
        uni.showToast({ title: '发送失败，请重试', icon: 'none' })
      }
    },

    startCountdown() {
      this.counting = true
      this.timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) this.resetCountdown()
      }, 1000)
    },

    resetCountdown() {
      clearInterval(this.timer)
      this.counting = false
      this.countdown = 60
    },

    async handleRegister() {
      const v1 = this.validateEmail()
      const v2 = this.validateCode()
      const v3 = this.validatePassword()
      const v4 = this.validateConfirm()
      if (!(v1 && v2 && v3 && v4)) return

      try {
        uni.showLoading({ title: '注册中...' })
        const res = await register({
          email: this.registerForm.email,
          captcha: this.registerForm.code,
          password: this.registerForm.password,
          role: this.registerForm.role
        })
        uni.hideLoading()
        if (res.code === 200) {
          uni.showToast({ title: '注册成功', icon: 'success' })
          setTimeout(() => uni.navigateTo({ url: '/pages/login/login-index/login-index' }), 1500)
        } else {
          uni.showToast({ title: res.message || '注册失败', icon: 'none' })
        }
      } catch (e) {
        uni.hideLoading()
        uni.showToast({ title: '注册异常，请重试', icon: 'none' })
      }
    },

    clearErrors() {
      this.errors = { email: '', code: '', password: '', confirmPassword: '' }
    },

    goLogin() {
      uni.navigateTo({ url: '/pages/login/login-index/login-index' })
    }
  },

  onUnload() {
    this.resetCountdown()
  }
}
</script>

<style scoped>
.container {
  margin: 100rpx;
}
.header {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 60rpx;
  text-align: center;
  margin-top: 15rpx;
}
.login-type-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
}

.switch-container {
  display: flex;
  width: 400rpx;
  height: 70rpx;
  position: relative;        
  border-radius: 35rpx;
  overflow: hidden;
}

.switch-option {
  flex: 1;
  text-align: center;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;       
  z-index: 1;
  transition: color .3s;
}

.switch-option.active {
  color: #b6ccd8;
  font-weight: bold;
}


.switch-option.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 120rpx;
  height: 4rpx;
  background-color: #b6ccd8;
  border-radius: 2rpx;
}
.switch-option.active {
  color: #b6ccd8;
  font-weight: bold;
}
.switch-option.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 120rpx;
  height: 4rpx;
  background-color: #b6ccd8;
  border-radius: 2rpx;
}
.input-group {
  margin-bottom: 40rpx;
  position: relative;
}
.label {
  display: block;
  font-size: 28rpx;
  color: #000;
  margin-bottom: 20rpx;
}
input {
  width: 100%;
  padding: 20rpx 0;
  border: none;
  font-size: 32rpx;
  outline: none;
  background: transparent;
  border-bottom: 2rpx solid #ccc;
}
.code-wrapper {
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid #e0e0e0;
}
.code-btn {
  margin-left: 20rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #b6ccd8;
  border-radius: 10rpx;
  white-space: nowrap;
}
.code-btn:disabled {
  color: #ccc;
  background-color: #f5f5f5;
}
.error-message {
  position: absolute;
  bottom: -35rpx;
  left: 0;
  font-size: 24rpx;
  color: #ff4d4f;
}
.login-btn {
  width: 100%;
  margin-bottom: 30rpx;
  padding: 20rpx;
  font-size: 32rpx;
  color: #fff;
  background-color: #b6ccd8;
  border-radius: 70rpx;
  border: 2rpx solid #1d1c1c;
}

.switch-form {
  margin-top: 30rpx;
  text-align: center;
  font-size: 28rpx;
  }
  .switch-btn {
    color: #b6ccd8;
    margin-left: 10rpx;
  }

.footer {
  margin-top: 60rpx;
  font-size: 24rpx;
  color: #999;
  text-align: center;
}
</style>